# -*- encoding: utf-8 -*-

# Copyright 2010 István Szentandrási
# <etude-music-player@googlegroups.com>

# This file is part of Etude.
#
# Etude is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as 
# published by the Free Software Foundation, either version 3 
# of the License, or (at your option) any later version.
#
# Etude is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Etude. If not, see <http://www.gnu.org/licenses/>.

from . import _

import etude.plugins as ep
import sys, traceback
MMKEYS = False
try:
    import mmkeys
    MMKEYS = True
except:
    pass



class MediaButtons(ep.PluginExtra):
    """
    Media buttons support under environments which doesn't support 
    gnome media keys through dbus.
    """
    _short_name = "Media Buttons (mmkeys)"
    _show_name = _("Media Buttons")
    _short_descr = _("Media buttons support under environments which doesn't support\
            gnome media keys through dbus.")
    _version = "0.1"
    _unique = "Media_Buttons-0.1" # short name + version is enough, just to identify loaded
    
    #unloading requires restart, so here is a workaround :P
    #we create a singleton of the class
    #unloading just makes the bindings to disconnect
    def __new__(cls, *args, **kw):
        if not hasattr(cls, '_instance'):
            orig = super(MediaButtons, cls)
            cls._instance = orig.__new__(cls, *args, **kw)
        return cls._instance

    def __init__(self, control):
        if hasattr(self, '_inited'):
            self.create_bindings()
            return
        self._inited = True
        
        ep.PluginExtra.__init__(self, control)
        if MMKEYS:
            self.keys = mmkeys.MmKeys()
            self.create_bindings()

    def create_bindings(self):
        pb = self.control.client.playback
        self.bind(self.keys, "mm_prev", lambda x, y: pb.prev())
        self.bind(self.keys, "mm_next", lambda x, y: pb.next())
        self.bind(self.keys, "mm_playpause", lambda x, y: pb.toggle())
        self.bind(self.keys, "mm_stop", lambda x, y: pb.stop())


    def unload(self):
        ep.PluginExtra.unload(self)


